const fs = require('fs')
const { crawler } = require('./crawler')
const schedule = require('node-schedule')
const { getFee } = require('./farmersworld')
const TelegramBot = require('node-telegram-bot-api')

const token = '5066194300:AAFrhneDGAgExCRxpGcOkZyxMugUcNYnTdI'

const bot = new TelegramBot(token, { polling: true })

const feeTopicList = process.env.NODE_ENV == 'prod' ? [-1001781952292] : [-620249350]
const reportTopicList = process.env.NODE_ENV == 'prod' ? [-1001781952292] : [-620249350]

const sleep = () => new Promise((res, rej) => setTimeout(res, 1000))

bot.onText(/\/echo (.+)/, (msg, match) => {
  // const chatId = msg.chat.id
  const resp = match[1]
  console.log('echo', msg.chat, resp)
  // bot.sendMessage(chatId, resp)
})

bot.onText(/\/fee/, async (msg) => {
  // 用户主动要去查询
  
  const fee = await getFee()
  await sendFee(fee, msg.chat.id)
})

bot.onText(/\/daily/, async (msg) => {
  const pages = await crawler()
  await sendReport(pages, msg.chat.id)
})

bot.onText(/\/active/, async (msg) => {
  const pages = await crawler('active')
  await sendReport(pages, msg.chat.id)
})

bot.onText(/\/income/, async (msg) => {
  const pages = await crawler('income')
  await sendReport(pages, msg.chat.id)
})

bot.onText(/\/flow/, async (msg) => {
  const pages = await crawler('flow')
  await sendReport(pages, msg.chat.id)
})

bot.onText(/\/river/, async (msg) => {
  const pages = await crawler('river')
  await sendReport(pages, msg.chat.id)
})

bot.onText(/\/rate/, async (msg) => {
  const pages = await crawler('rate')
  await sendReport(pages, msg.chat.id)
})

bot.on('text', function (msg) {
  console.log('Received message')
  console.log('  chat ID:', msg.chat.id)
  console.log('  text:', msg.text)
})

// bot.on('message', (msg) => {
//   // const chatId = msg.chat.id;
//   // if (msg.chat) {
//   // }
//   console.log(msg.chat);
//   // send a message to the chat acknowledging receipt of their message
//   // bot.sendMessage(chatId, 'Received your message');
// });

bot.on('polling_error', (error) => {
  console.log(error.code) // => 'EFATAL'
})

// 定时检查，如果是5才发送
async function scheduleJobFee() {
  const fee = await getFee()
  console.log('check fee ...', fee, new Date())
  if (fee === 5) {
    for (const chatId of feeTopicList) {
      await sendFee(fee, chatId)
    }
  }
}

// 定时发送日报
async function scheduleJobDaily() {
  console.log('daily report ...', new Date())
  const pages = await crawler()
  for (const chatId of reportTopicList) {
    await sendReport(pages, chatId)
  }
}
// 发送报告
async function sendReport(pages, chatId) {
  for (const { id, name } of pages) {
    console.log('StarterBot send Report', chatId, name)
    await bot.sendPhoto(chatId, fs.createReadStream(`./screenshots/${id}.png`))
    await sleep(1)
    await bot.sendMessage(chatId, name)
  }
}
// 发送费率
async function sendFee(fee, chatId) {
  console.log('StarterBot Send Fee Remind...' + chatId)
  const msg = (fee === 5 ? '✅' : '❌') + 'Latest Fee: ' + fee + '%'
  await bot.sendMessage(chatId, msg)
}

if (process.env.NODE_ENV == 'prod') {
  // 定时检查费率
  schedule.scheduleJob('1 1 11 * * *', scheduleJobDaily)
  schedule.scheduleJob('1 1 23 * * *', scheduleJobDaily)
  schedule.scheduleJob('1 5 * * * *', scheduleJobFee)
} else {
  // schedule.scheduleJob('1 * * * * *', scheduleJobDaily)
}
